import React from 'react';
import {Button,Icon,message,Alert} from 'antd'
import {toJS} from 'mobx';
import add from './img/add.png'
import dateWorkBg from './img/dateWorkBg.png'
import './style/';
import { Calendar as AntdCalendar } from 'antd';
import {WeaTools, WeaDialog, WeaLocaleProvider} from "ecCom";
import Setting_Tab from "./Setting_Tab";
const getLabel = WeaLocaleProvider.getLabel;
class Calendar extends React.Component {

constructor(props) {
    super(props);
}

    state = {
        data:[],
        visible:false,
        richenId:"",
        count:"0",
        iscCount:"0",
        bgColor:"#ffffff",
        bgTmd:"100",
        currentOptionDate:new Date(),
        hasDataDate : [],
        setting: {
            showType: '0',
        }
    }


    componentWillMount(){
        this.saveSetting(false)
    }

    //转换日期格式作为调用日程接口时间参数
    changeDate = (_date, format)=> {
        var date = {
            "M+": _date.getMonth() + 1,
            "d+": _date.getDate(),
            "h+": _date.getHours(),
            "m+": _date.getMinutes(),
            "s+": _date.getSeconds(),
            "q+": Math.floor((_date.getMonth() + 3) / 3),
            "S+": _date.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (_date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    getDatas = () => {
        const {currentOptionDate} = this.state
        let selectdate = this.changeDate(currentOptionDate, "yyyy-MM-dd");
        WeaTools.callApi('/api/portal/calendar/getcalendar','GET',{
            "id":this.props.id
        }).then((result) => {
            if(result.api_status==true){
                let bg = result.data.bgColor.split(',');
                let isCount = result.data.isCount
                let setting = JSON.parse(result.data.setting)
                this.setState({iscCount:isCount,bgColor:bg[0],bgTmd:bg[1],setting:setting});
                //显示本周日程数
                if(isCount && isCount == '1'){
                    WeaTools.callApi('/api/workplan/calendar/getWorkPlanWeekCount', 'POST', {selectDate: selectdate}).then(result=> {
                         this.setState({count: result.count})
                    })
                }
                //显示日程类型
                let params = {}
                if(setting.showType && setting.showType == '1'){
                   params = {from:'PORTAL'}
                }
                WeaTools.callApi('/api/workplan/calendar/MyCalendar', 'POST', {viewType: '1', selectDate: selectdate,...params}).then((result) => {
                    this.setState({data:result.events})
                    let ids = ""
                    for(let index in result.events){
                        ids += ","+result.events[index][0]
                    }
                    if(ids !=""){
                        ids = ids.substring(1)
                    }
                    WeaTools.callApi('/api/portal/calendar/getCalendarMeetName', 'POST', {ids:ids }).then((result) => {
                        if(result && result.data){
                            this.setState({"calendarMeetName":result.data})
                        }
                    });
                })
                WeaTools.callApi('/api/workplan/calendar/MyCalendar', 'POST', {viewType: '3', selectDate: selectdate,...params}).then((result)=>{
                    let temp = ""
                    if(result.events && result.events.length > 0){
                        for(let i = 0 ; i< result.events.length ;i++){
                            temp += "," + result.events[i][2]
                            temp += "," + result.events[i][3]
                        }
                    }
                    this.setState({hasDataDate:temp})
                })
            }
        });
    }


    saveSetting= (tip) =>{
        WeaTools.callApi('/api/portal/calendar/savecalendar','POST',{
            jsonStr: JSON.stringify({
                "isCount":this.state.iscCount,
                "id":this.props.id,
                "bgColor":this.state.bgColor+","+this.state.bgTmd,
                "setting": JSON.stringify(this.state.setting),
                "init":!tip
            })
        }).then(result => {
            if(tip){
                if(result.api_status==true){
                    this.setState({visible:false});
                    this.getDatas();
                    message.success(getLabel(83551,"保存成功！"),2);
                }else {
                    message.error(getLabel(84544,"保存失败！"),2);
                }
            }

        })

    }

    //初始化获取数据
    componentDidMount(){
        this.getDatas();
    }

    onClose = () => {

    }

    //跳转more页面
    moreUrl = () => {
    window.open("/wui/index.html#/main/wp/myWorkPlan");
    }
    getDate = (value) => {
    let time = value.split(' ');
     return time[1];
    }

    //跳转对应的日程
    openRiChen = (id) => {
    window.open("/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?workPlanId="+id);
    }

    onCancel = () => {
    this.getDatas();
    this.setState({visible:false});
    }

    changeBgColor = (value) => {
    this.setState({bgColor: value});
    }

    changeCount = (value) => {
    this.setState({iscCount:value});
    }

    setSetting = (value)=>{
        let setting = {...this.state.setting,...value}
        this.setState({setting})
    }

    openDia = () => {
    this.setState({visible:true});
    }

     changeBgTmd = (value) => {
        this.setState({bgTmd: value});
     }




    colorToRGB() {
        let color = this.state.bgColor
        let tmd = parseInt(this.state.bgTmd)/100;
        var color1, color2, color3;
        color = ""+color;
        if (typeof color !== "string") return;
        if (color.charAt(0) == "#") {
            color = color.substring(1);
        }
        var not16num = color.split("").filter(function (item, index) {
            return isNaN(parseInt(item, 16))
        });
        if(not16num.length) return;
        switch (color.length) {
            case 3:
                color1 = color.substr(0,1);
                color2 = color.substr(1,1);
                color3 = color.substr(2,1);
                color1 = color1 + color1;
                color2 = color2 + color2;
                color3 = color3 + color3;
                break;
            case 6:
                color1 = color.substr(0,2);
                color2 = color.substr(2,2);
                color3 = color.substr(4,2);
                break;
            default:
                return false;
        }
        color1 = parseInt(color1, 16);
        color2 = parseInt(color2, 16);
        color3 = parseInt(color3, 16);
        return "rgba("+color1+","+color2+","+color3+","+tmd+")";
    }

     handlerSelectDate = (date)=>{
         this.state.currentOptionDate = new Date(date.time)
         this.setState({currentOptionDate:new Date(date.time)})
         this.getDatas()
     }
     handlerChangeDate = (condition)=>{
         let {currentOptionDate} = this.state
         if(condition =='left'){
             currentOptionDate.setDate(currentOptionDate.getDate()-1)
         }else if(condition =='right'){
             currentOptionDate.setDate(currentOptionDate.getDate()+1)
         }
         this.setState({currentOptionDate:currentOptionDate})
         this.getDatas()
     }
    dateCellRender = (date)=>{
        const {hasDataDate=""} = this.state
        let currentDate = new Date(date.time)
        const year = currentDate.getFullYear()
        let month = currentDate.getMonth()+1+''
        let d = currentDate.getDate() + ''
        const ymd = year+"-"+month+"-"+d
        if(month.length != 2){
            month = '0' + month
        }
        if(d.length != 2){
            d = '0' + d
        }
        const mdy = month+"/"+d+"/"+year
        $(`.customComponent-calendar-${this.props.id}  .ant-fullcalendar-cell[title=${ymd}] .ant-fullcalendar-value`).removeClass("ant-fullcalendar-event")
        if(hasDataDate.indexOf(mdy)!=-1){
            $(`.customComponent-calendar-${this.props.id}  .ant-fullcalendar-cell[title=${ymd}] .ant-fullcalendar-value`).addClass("ant-fullcalendar-event")
        }
        // WeaTools.callApi('/api/workplan/calendar/MyCalendar', 'POST', {viewType: '1', selectDate:  this.changeDate(currentDate, "yyyy-MM-dd")}).then((result) => {
        //     $(`.customComponent-calendar-${this.props.id}  .ant-fullcalendar-cell[title=${ymd}] .ant-fullcalendar-value`).removeClass("ant-fullcalendar-event")
        //     if(result.events.length > 0 ){
        //         $(`.customComponent-calendar-${this.props.id}  .ant-fullcalendar-cell[title=${ymd}] .ant-fullcalendar-value`).addClass("ant-fullcalendar-event")
        //     }
        // })

    }


    getMonthAndData = (temp)=>{
        let dates = temp.split("/")
        return parseInt(dates[0])+"月"+parseInt(dates[1])+"日"
    }

    getHourAndMinues = (temp,temp2)=>{
        let dates = temp.split(" ")
        let hours = dates[1].split(":")
        let hour = parseInt(hours[0])
        let minues = hours[1]
        let dates2 = temp2.split(" ")
        let hours2 = dates2[1].split(":")
        let hour2 = parseInt(hours2[0])
        let minues2 = hours2[1]

        return (hour >12 ? 'PM ' :'AM ') + hour +":"+minues+"-"+hour2+":"+minues2
    }


    render() {
        const {data,count,visible,iscCount,currentOptionDate,calendarMeetName={},setting} = this.state;
        let beginDate = currentOptionDate.getFullYear()+"-"+((currentOptionDate.getMonth()+1) <10?("0"+(currentOptionDate.getMonth()+1)):(currentOptionDate.getMonth()+1))+"-"+((currentOptionDate.getDate()<10)?("0"+(currentOptionDate.getDate())):(currentOptionDate.getDate()))
        let beginTime = ((new Date().getHours()<10)?("0"+new Date().getHours()):(new Date().getHours()))+":"+new Date().getMinutes()
        let endDate = currentOptionDate.getFullYear()+"-"+((currentOptionDate.getMonth()+1) <10?("0"+(currentOptionDate.getMonth()+1)):(currentOptionDate.getMonth()+1))+"-"+((currentOptionDate.getDate()<10)?("0"+(currentOptionDate.getDate())):(currentOptionDate.getDate()))
        let endTime = "23:59"

        let display ="";
        if(this.props.isSetting==false){
            display="none";
        }
        let datas = data;
        if(data.length>5){
            datas = data.slice(0,5);
        }
        const bgcolor = this.colorToRGB()
        return (
            <div className={`portal-com-calendar customComponent-calendar-${this.props.id}`} style={{"background-color":bgcolor,"border-radius": 12}}>
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@wk0u6f`}  className="calendar-setting-Icon" onClick={this.openDia} type="setting" theme="filled" style={{"display":display}}/>


                {iscCount=="1"? <div className="portal-com-calendar-count">{count}</div>:<div></div>}
                <div className="portal-com-calendar-content" style={{height:'100%'}}>
                    {/*<div className="portal-com-calendar-header">*/}
                        {/*<span className="portal-com-calendar-more"   style={{"font-size":12,"top":5}} >*/}
                            {/*<span onClick={this.moreUrl}>{getLabel(385419,"更多>>")}</span></span>*/}
                    {/*</div>*/}
                    <div style={{width:'calc(100% - 50px)',height:'60px',position:'relative','margin':'0 25px'}}>
                        <div style={{position:'absolute',left:'0px',top:'20px','font-size':'18px',color:'#000','font-weight':'bold','font-family':'微软雅黑'}}>{currentOptionDate.getFullYear()}年{currentOptionDate.getMonth()+1}月</div>
                        <div style={{position:'absolute',right:'75px',top:'20px'}}>
                            <span style={{'font-size':'21px',color:'#727888',cursor:'pointer'}} onClick={()=>{this.handlerChangeDate("left")}}>&lt;</span>
                            <div style={{display:'inline-block',width:'50px','font-size':'18px',color:'#000','font-weight':'bold','font-family':'微软雅黑','text-align':'center'}}>{currentOptionDate.getDate()}</div>
                            <span style={{'font-size':'21px',color:'#727888',cursor:'pointer'}}  onClick={()=>{this.handlerChangeDate("right")}}>&gt;</span>
                        </div>
                        <div style={{display:'inline-block',position:'absolute',right:'0px',top:'20px'}}>
                            <img style={{sursor:'pointer'}} onClick={()=>{window.open(`/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?type=create&selectedUser=&beginDate=${beginDate}&beginTime=${beginTime}&endDate=${endDate}&endTime=${endTime}`,'_blank')}} src={add}/>
                        </div>
                    </div>

                    <AntdCalendar ecId={`${this && this.props && this.props.ecId || ''}_AntdCalendar@zutxoq`} fullscreen={false} value={currentOptionDate} onSelect={(date)=>{this.handlerSelectDate(date)}} dateCellRender={this.dateCellRender} />

                    <div style={{border:'0.5px solid #e8e8e8','margin':'0px 20px'}}></div>
                    <div style={{height:'calc(100% - 329px)','overflow-y':'auto'}}>
                        <div style={{'margin':'0px 25px'}}>
                            {
                                data.length>0? datas.map((item) => {
                                    return (
                                        <div style={{cursor:'pointer','background-image':`url(${dateWorkBg})`,'background-repeat':'no-repeat',height:'120px','background-size':'100% 100%'}} onClick={() => this.openRiChen(item[0])}>
                                            <div style={{width:'30%',display:'inline-block',height:'120px','text-align':'center'}}>
                                                <div style={{display:'inline-block',width:'100%','vertical-align':'middle'}}>
                                                    <div style={{'font-size':'15px'}}>{this.getMonthAndData(item[2])}</div>
                                                    <div style={{'font-size':'13px',color:'rgb(204, 204, 204)','margin-top':'3px'}}>{this.getHourAndMinues(item[2],item[3])}</div>
                                                </div>

                                                <div style={{display:'inline-block',height:'100%',width:"0px",'vertical-align':'middle'}}></div>
                                            </div>
                                            <div style={{display:'inline-block','border-left':'1px solid #7d7d7d',height:'60px','vertical-align':'middle'}}></div>
                                            <div  style={{display:'inline-block',width:'calc(70% - 15px)',height:'120px','text-align':'left','vertical-align':'middle'}}>
                                                <div style={{display:'inline-block',width:'100%','padding-left':'30px','vertical-align':'middle'}}>
                                                    <div style={{'font-size':'15px',overflow: 'hidden','text-overflow': 'ellipsis', 'white-space': 'nowrap'}} title={(setting.showType == '1' ? '('+item[12]+')':'')+item[1]}>{setting.showType == '1' ? '('+item[12]+')':''}{item[1]}</div>
                                                    <div style={{'font-size':'13px',overflow: 'hidden','text-overflow': 'ellipsis', 'white-space': 'nowrap',color:'rgb(204, 204, 204)','margin-top':'3px'}} title={calendarMeetName[item[0]]+(calendarMeetName[item[0]]?"会议室":"")}>{calendarMeetName[item[0]]}{calendarMeetName[item[0]]?"会议室":""}</div>
                                                </div>
                                                <div style={{display:'inline-block',height:'100%',width:"0px",'vertical-align':'middle'}}></div>
                                            </div>
                                        </div>
                                    );
                                }):  <div className="todo-item">
                                    <div className="Dian"></div>
                                    <span  className="_content">{getLabel(83553,"暂无数据")}</span>
                                </div>
                            }
                        </div>
                    </div>
                </div>

                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@qbhu1x`} visible={visible} style={{height:220}} onCancel={this.onCancel} title={getLabel(30747,"设置")}>
                    <div style={{position:"relative",height:220}}>
                        <Setting_Tab ecId={`${this && this.props && this.props.ecId || ''}_Setting_Tab@67m75l`} data={this.state} changebgColor={this.changeBgColor} changeCount={this.changeCount} changeBgTmd={this.changeBgTmd} setSetting={this.setSetting}/>
                        <div style={{position:"absolute",bottom:7,"margin-left": "67%"}}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0130gz`}  type="primary" onClick={()=>{this.saveSetting(true)}}>{getLabel(33703,"确认")}</Button>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u253zy`} onClick={this.onCancel} style={{"margin-left":10}}>{getLabel(31129,"取消")}</Button>
                        </div>
                    </div>
                </WeaDialog>
                </div>
        );
    }

}

export default Calendar;